/**
 *
 */
package com.nishop.service;

import com.google.common.collect.Maps;
import com.nishop.api.ITopicsService;
import com.nishop.api.entity.Topic;
import com.nishop.api.entity.TopicExample;
import com.nishop.api.form.TopicsRequestForm;
import com.nishop.api.util.Identity;
import com.nishop.service.dao.TopicMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 李建成
 *
 */
@Service
public class TopicServiceImpl implements ITopicsService {

    @Autowired
    private TopicMapper topicMapper;

    @Override
    public List<Topic> queryTopicList(TopicsRequestForm requestForm) {

        Map<String, Object> param = builderMap(requestForm);
        List<Topic> topics = topicMapper.queryTopicsByPage(param);

        return topics;
    }

    private Map<String, Object> builderMap(TopicsRequestForm requestForm) {
        Map<String, Object> param = Maps.newHashMap();

        if (requestForm.getPage() != null && requestForm.getLimit() != null) {
            param.put("start", (requestForm.getPage() - 1) * requestForm.getLimit());
            param.put("limit", requestForm.getLimit());
        }
        if (StringUtils.isNotBlank(requestForm.getTitle())) {
            param.put("goodsName", requestForm.getTitle());
        }
        return param;
    }

    private TopicExample getTopicExample() {
        TopicExample example = new TopicExample();
        return example;
    }

    @Override
    public long queryCount() {

        TopicExample example = getTopicExample();

        long count = topicMapper.countByExample(example);

        return count;
    }

    @Override
    public Boolean edit(Topic category) {
        TopicExample example = new TopicExample();

        example.createCriteria().andIdEqualTo(category.getId());

        return topicMapper.updateByExampleWithBLOBs(category,example) > 0;
    }

    @Override
    public Boolean add(Topic category) {
        category.setId(Identity.uuidWithoutHyphen());
        return topicMapper.insert(category) > 0;
    }

    @Override
    public Boolean del(Topic category) {

        String id = category.getId();

        if (Objects.isNull(id)) {
            return false;
        }
        TopicExample e = new TopicExample();
        e.createCriteria().andTopicCategoryIdEqualTo(id);
        return topicMapper.deleteByExample(e) > 0;
    }
}
